package com.gwlc.common.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>lucky-com.gwlc.common.util-CookieUtil</p>
 * <p>Description:  </p>
 * <p>Copyright: Copyright (c) 2021</p>
 * <p>Company: hanchunit@163.com</p>
 *
 * @author hanchun
 * @version 1.0
 * @date 2021/9/8
 */
public class CookieUtil {
    /**
     * 10天存活时间
     */
    public static final int TIME = 60 * 60 * 24 * 10;

    /**
     * 添加cookie
     *
     * @param response
     * @param cookieName
     * @param value
     */
    public static void addCookie(HttpServletResponse response,
                                 String cookieName, String value) {
        Cookie cookie = new Cookie(cookieName, value);
        cookie.setPath("/");
        cookie.setMaxAge(TIME);
        response.addCookie(cookie);
    }

    /**
     * 删除cookie
     *
     * @param response
     * @param cookieName
     */
    public static void deleteCookie(HttpServletResponse response,
                                    String cookieName) {
        Cookie cookie = new Cookie(cookieName, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    /**
     * 获取用户的cookie名字
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static String getByName(HttpServletRequest request, String cookieName) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookieName.equals(cookie.getName())) {
                    value = cookie.getValue();
                }
            }
        }
        return value;
    }

}
